<template>
  <el-select
    :disabled="disabled"
    :placeholder="place"
    :style="$attrs.style"
    :clearable="clearable"
    :class="$attrs.class"
    :multiple="multiple"
    @change="chooseChange"
    v-model="curVal"
  >
    <el-option
      v-for="item in roles"
      :key="item.Id"
      :label="item.RoleName"
      :title="item.Remark"
      :value="item.Id"
    />
  </el-select>
</template>

<script>
import { getSelect } from '@/api/role/role'
import { array } from 'vue-types'
export default {
  props: {
    clearable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    modelValue: {
      default: null
    },
    placeholder: {
      type: String,
      default: '选择字典'
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      place: null,
      roles: [],
      curVal: null
    }
  },
  watch: {
    placeholder: {
      handler(val) {
        this.place = val
      },
      immediate: true
    },
    modelValue: {
      handler(val) {
        this.curVal = val
      },
      immediate: true
    }
  },
  mounted() {
    this.loadRole()
  },
  methods: {
    async loadRole() {
      const roles = await getSelect()
      if (roles.length > 0) {
        roles.forEach((e) => {
          if (e.IsAdmin) {
            e.RoleName = e.RoleName + '(管理员)'
          }
        })
      }
      this.roles = roles
    },
    chooseChange(value) {
      let item = null
      if (value != null) {
        if (this.multiple) {
          item = this.roles.filter((c) => value.includes(c.Id))
        } else {
          item = this.roles.find((c) => c.Id == value)
        }
      }
      this.$emit('update:modelValue', value)
      this.$emit('change', value, item)
    }
  }
}
</script>
